import React, { useEffect, useMemo, useState } from 'react'
import { Link, useHistory } from 'react-router-dom'
import { useSelector, useDispatch } from 'react-redux'
import classNames from 'classnames'
import { Header, Loading, AlertTip, RouterView } from 'src/components'
import { CSSTransition } from "react-transition-group";
import { imgBaseUrl } from 'src/config/env'
import { INIT_BUYCART, SAVE_GEOHASH, CHOOSE_ADDRESS, NEED_VALIDATION, SAVE_CART_ID_SIG, SAVE_ORDER_PARAM, ORDER_SUCCESS, SAVE_SHOPID } from 'src/redux/action-type'
import { useQuery } from 'src/utils/hooks'
import { checkout, placeOrders, getAddressList } from 'src/api/getData'
import routerData from './routerData'
import './index.scss'

const ConfirmOrder = () => {
    const history = useHistory();
    const query = useQuery();
    const [shopId, setShopId] = useState()
    const [showLoading, setShowLoading] = useState(true)
    const [checkoutData, setCheckoutData] = useState()
    const [shopCart, setShopCart] = useState()
    const [showPayWay, setShowPayWay] = useState(false)
    const [payWayId, setPayWayId] = useState(1)
    const [showAlert, setShowAlert] = useState(false)
    const [alertText, setAlertText] = useState()
    const { cartList, remarkText, inputText, choosedAddress, userInfo,geohash } = useSelector((state) => state)
    const dispatch = useDispatch();


    useEffect(() => {
        //获取地址信息，第一个地址为默认选择地址
        const initAddress = async () => {
            if (userInfo && userInfo.user_id) {
                const addressRes = await getAddressList(userInfo.user_id);
                if (addressRes instanceof Array && addressRes.length) {
                    dispatch({
                        type: CHOOSE_ADDRESS,
                        address: addressRes[0],
                        index: 0
                    })
                }
            }
        }
        initAddress()
    }, [userInfo, dispatch])




    useEffect(() => {
        //获取上个页面传递过来的geohash值
       
        //获取上个页面传递过来的shopid值
        setShopId(query.shopId)
        dispatch({
            type: INIT_BUYCART
        })
        dispatch({
            type: SAVE_SHOPID,
            shopid: query.shopId
        })
        //获取当前商铺购物车信息
        setShopCart(cartList[query.shopId])
    }, [cartList, dispatch, geohash, query.shopId])

    useEffect(() => {
        if (geohash) {
            //初始化数据
            const initData = async () => {
                let newArr = [];
                Object.values(shopCart).forEach(categoryItem => {
                    Object.values(categoryItem).forEach(itemValue => {
                        Object.values(itemValue).forEach(item => {
                            newArr.push({
                                attrs: [],
                                extra: {},
                                id: item.id,
                                name: item.name,
                                packing_fee: item.packing_fee,
                                price: item.price,
                                quantity: item.num,
                                sku_id: item.sku_id,
                                specs: [item.specs],
                                stock: item.stock,
                            })
                        })
                    })
                })
                //检验订单是否满足条件
                let res = await checkout(geohash, [newArr], shopId);
                setCheckoutData(res)
                dispatch({
                    type: SAVE_CART_ID_SIG,
                    cart_id: res.cart.id,
                    sig: res.sig
                })

                setShowLoading(false)
            }
            initData();
            dispatch({
                type: SAVE_GEOHASH,
                geohash
            })
        }
        if (!(userInfo && userInfo.user_id)) {
            // setShowAlert(true);
            // setAlertText('您还没有登录');
        }
    }, [geohash, userInfo, shopCart, shopId, dispatch])

    //备注页返回的信息进行处理
    const remarklist = useMemo(() => {
        let str = '';
        if (remarkText) {
            Object.values(remarkText).forEach(item => {
                str += item[1] + '，';
            })
        }
        //是否有自定义备注，分开处理
        if (inputText) {
            return str + inputText;
        } else {
            return str.substr(0, str.lastIndexOf('，'));
        }
    }, [remarkText, inputText])

    //显示付款方式
    const showPayWayFun = () => {
        setShowPayWay(!showPayWay)
    }
    //选择付款方式
    const choosePayWay = (is_online_payment, id) => {
        if (is_online_payment) {
            setShowPayWay(!showPayWay)
            setPayWayId(id)
        }
    }
    //地址备注颜色
    const iconColor = (name) => {
        switch (name) {
            case '公司': return '#4cd964';
            case '学校': return '#3190e8';
            default: return "#3190e8"
        }
    }
    //确认订单
    const confrimOrder = async () => {
        //用户未登录时弹出提示框
        if (!(userInfo && userInfo.user_id)) {
            setShowAlert(true)
            setAlertText('请登录')
            return
            //未选择地址则提示
        } else if (!choosedAddress) {
            setShowAlert(true)
            setAlertText('请添加一个收货地址')
            return
        }
        //保存订单
        dispatch({
            type: SAVE_ORDER_PARAM,
            user_id: userInfo.user_id,
            cart_id: checkoutData.cart.id,
            address_id: choosedAddress.id,
            description: remarklist,
            entities: checkoutData.cart.groups,
            geohash: geohash,
            sig: checkoutData.sig,
        })

        //发送订单信息
        let orderRes = await placeOrders(userInfo.user_id, checkoutData.cart.id, choosedAddress.id, remarklist, checkoutData.cart.groups, geohash, checkoutData.sig);
        //第一次下单的手机号需要进行验证，否则直接下单成功
        if (orderRes.need_validation) {
            dispatch({
                type: NEED_VALIDATION,
                needValidation: orderRes
            })
            history.push('/confirmOrder/userValidation');
        } else {
            dispatch({
                type: ORDER_SUCCESS,
                order: orderRes
            })
            history.push('/confirmOrder/payment');
        }
    }

    const closeTip = () => {
        setShowAlert(false)
    }

    return <div className="page_confirmorder">
        {
            !showLoading && <section>
                <Header title="确认订单" goBack signinUp='confirmOrder'></Header>
                <Link
                    to={`/confirmOrder/chooseAddress?id=${checkoutData.cart.id}&sig=${checkoutData.sig}`}
                    className="address_container">
                    <div className="address_empty_left">
                        <svg className="location_icon">
                            <use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#location"></use>
                        </svg>
                        {!choosedAddress ? <div className="add_address">请添加一个收货地址</div> :
                            <div className="address_detail_container">
                                <header>
                                    <span>{choosedAddress.name}</span>
                                    <span>{choosedAddress.sex === 1 ? '先生' : '女士'}</span>
                                    <span>{choosedAddress.phone}</span>
                                </header>
                                <div className="address_detail">
                                    {choosedAddress.tag && <span style={{
                                        backgroundColor: iconColor(choosedAddress.tag)
                                    }}>{choosedAddress.tag}</span>}
                                    <p>{choosedAddress.address_detail}</p>
                                </div>
                            </div>
                        }
                    </div>
                    <svg className="address_empty_right">
                        <use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#arrow-right"></use>
                    </svg>
                </Link>
                <section className="delivery_model container_style">
                    <p className="deliver_text">送达时间</p>
                    <section className="deliver_time">
                        <p>尽快送达 | 预计 {checkoutData.delivery_reach_time}</p>
                        {checkoutData.cart.is_deliver_by_fengniao && <p>蜂鸟专送</p>}
                    </section>
                </section>
                <section className="pay_way container_style">
                    <header className="header_style">
                        <span>支付方式</span>
                        <div className="more_type" onClick={showPayWayFun}>
                            <span>在线支付</span>
                            <svg className="address_empty_right">
                                <use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#arrow-right"></use>
                            </svg>
                        </div>
                    </header>
                    <section className="hongbo">
                        <span>红包</span>
                        <span>暂时只在饿了么 APP 中支持</span>
                    </section>
                </section>
                <section className="food_list">
                    {checkoutData.cart.restaurant_info && <header>
                        <img src={`${imgBaseUrl}${checkoutData.cart.restaurant_info.image_path}`} alt="" />
                        <span>{checkoutData.cart.restaurant_info.name}</span>
                    </header>}
                    {checkoutData.cart.groups && <ul className="food_list_ul">
                        {
                            checkoutData.cart.groups[0].map(item => {
                                return <li key={item.id} className="food_item_style">
                                    <p className="food_name ellipsis">{item.name}</p>
                                    <div className="num_price">
                                        <span>x {item.quantity}</span>
                                        <span>¥{item.price}</span>
                                    </div>
                                </li>
                            })
                        }
                    </ul>}
                    {checkoutData.cart.extra && <div className="food_item_style">
                        <p className="food_name ellipsis">{checkoutData.cart.extra[0].name}</p>
                        <div className="num_price">
                            <span></span>
                            <span>¥ {checkoutData.cart.extra[0].price}</span>
                        </div>
                    </div>}
                    <div className="food_item_style">
                        <p className="food_name ellipsis">配送费</p>
                        <div className="num_price">
                            <span></span>
                            <span>¥ {checkoutData.cart.deliver_amount || 0}</span>
                        </div>
                    </div>
                    <div className="food_item_style total_price">
                        <p className="food_name ellipsis">订单 ¥{checkoutData.cart.total}</p>
                        <div className="num_price">
                            <span>待支付 ¥{checkoutData.cart.total}</span>
                        </div>
                    </div>
                </section>
                <section className="pay_way container_style">
                    <Link
                        to={`/confirmOrder/remark?id=${checkoutData.cart.id}&sig=${checkoutData.sig}`}
                        className="header_style">
                        <span>订单备注</span>
                        <div className="more_type">
                            <span className="ellipsis">{remarkText || inputText ? remarklist : '口味、偏好等'}</span>
                            <svg className="address_empty_right">
                                <use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#arrow-right"></use>
                            </svg>
                        </div>
                    </Link>
                    <Link
                        to={checkoutData.invoice.is_available ? '/confirmOrder/invoice' : ''}
                        className={classNames('hongbo', {
                            support_is_available: checkoutData.invoice.is_available
                        })}
                    >
                        <span>发票抬头</span>
                        <span>
                            {checkoutData.invoice.status_text}
                            <svg className="address_empty_right">
                                <use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#arrow-right"></use>
                            </svg>
                        </span>
                    </Link>
                </section>
                <section className="confrim_order">
                    <p>待支付 ¥{checkoutData.cart.total}</p>
                    <p onClick={confrimOrder}>确认下单</p>
                </section>
                <CSSTransition classNames="fade" in={showPayWay} timeout={500} unmountOnExit>
                    <div className="cover" onClick={showPayWayFun}></div>
                </CSSTransition>
                <CSSTransition classNames="slid_up" in={showPayWay} timeout={500} unmountOnExit>
                    <div className="choose_type_Container">
                        <header>支付方式</header>
                        <ul>
                            {
                                checkoutData.payments.map(item => {
                                    return <li key={item.id} className={classNames({ choose: payWayId === item.id })}>
                                        <span>{item.name}{!item.is_online_payment && <span>{item.description}</span>}</span>
                                        <svg className="address_empty_right" onClick={() => choosePayWay(item.is_online_payment, item.id)}>
                                            <use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#select"></use>
                                        </svg>
                                    </li>
                                })
                            }
                        </ul>
                    </div>
                </CSSTransition>
            </section>
        }

        {
            showLoading && <Loading />
        }
        {
            showAlert && <AlertTip onClose={closeTip} alertText={alertText}></AlertTip>
        }
        <RouterView data={routerData} />
    </div>
}

export default ConfirmOrder